import axios from "axios";

import { layer } from "vue3-layer";

const instance = axios.create({
    baseURL: 'http://localhost:8000',
    timeout: 10000,
    // 设置特殊的 头信息、用来告诉 服务器 当前 请求采用 异步请求
    headers: {'X-Requested-With': 'XMLHttpRequest'}
})

instance.interceptors.request.use(function (config) {
    // Do something before request is sent'
    if (config.loading){
        // 开启 一个 loading 效果
        config.loadingIndex = layer.load(2);
    }

    return config;
  }, function (error) {
    // Do something with request error
    return Promise.reject(error);
  });

instance.interceptors.response.use(function (response) {
    if(response.config.loadingIndex){
        layer.close(response.config.loadingIndex);
    }
    return response.data;
  }, function (error) {
    if (error.status && error.status == 404){
        layer.msg("信息找不到", {icon: 2});
    }else if (error.status && (error.status == 405 || error.status == 401)){
        layer.msg(error.response.data.detail, {icon: 2, time: 1000});
    }else if (error.status && error.status == 400){
        let data = error.response.data;
        for(let [key, value] of Object.entries(data)){
            layer.msg(`${key}：${value}`, {icon: 2});
            break; // 只显示第一个错误信息
        }
    }else if (error.status && error.status == 500){
        layer.msg('服务器异常', {icon: 2});
    }else {
        layer.msg('未知错误', {icon : 2})
    }
    if(error.response && error.response.config.loadingIndex){
        layer.close(error.response.config.loadingIndex);
    }
    return Promise.reject(error);
  });

  export default instance;


